﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Common.Tools
{
   public static class CacheHelper
    {
        /// <summary>
        /// 根据CacheId,获得对应的cache对象。
        /// </summary>
        /// <param name="CacheId"></param>
        /// <returns></returns>
       public static object GetCache(string CacheId)
        {
            //获得对应的Cache object 对象。
            object objCache = System.Web.HttpRuntime.Cache.Get(CacheId); 

            // 判斷 Cache 是否啟用 ,如果配置文件中不再起作用，就删除对应的key的Cache obj,如果启用，不做任何处理。
            if (ConfigurationManager.AppSettings["EnableCache"] == null
                || !Convert.ToBoolean(ConfigurationManager.AppSettings["EnableCache"]))
            {
                objCache = null;
                System.Web.HttpRuntime.Cache.Remove(CacheId);
            }

            return objCache;
        }

        /// <summary>
        /// 寫入 Cache 資料 ( 預設 60 秒 )
        /// </summary>
        /// <param name="CacheId">缓存Key</param>
        /// <param name="objCache">缓存对象</param>
       public static void SetCache(string CacheId, object objCache)
        {
            if (ConfigurationManager.AppSettings["CacheDurationSeconds"] != null)
            {
                SetCache(CacheId, objCache,
                    Convert.ToInt32(ConfigurationManager.AppSettings["CacheDurationSeconds"]));
            }
            else
            {
                SetCache(CacheId, objCache, 60);
            }
        }

        /// <summary>
        /// 设置缓存信息
        /// </summary>
        /// <param name="CacheId">缓存唯一Key</param>
        /// <param name="objCache">缓存对象</param>
        /// <param name="cacheDurationSeconds">缓存时间</param>
       public static void SetCache(string CacheId, object objCache, int cacheDurationSeconds)
        {
            if (objCache != null)
            {
                //插入缓存对象
                System.Web.HttpRuntime.Cache.Insert(
                    CacheId,
                    objCache,
                    null,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    new TimeSpan(0, 0, cacheDurationSeconds),
                    System.Web.Caching.CacheItemPriority.High,
                    null);
            }
        }
    }
}

